package listeners;

import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.TerminalNode;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

// test expr using visitor
public class TestEvalVisitor {

    public static class EvalVisitor extends ExprBaseVisitor<Integer> {
        @Override
        public Integer visitE(ExprParser.EContext ctx) {
            System.out.println("current node :" + ctx.getText() + "\n current children:" + ctx.children);
            if (ctx.getChildCount() == 3) {
                System.out.println("e of node " + ctx.e());
                if (ctx.op.getType() == ExprParser.MULT) {
                    // multiple
                    return visit(ctx.e(0)) * visit(ctx.e(1));
                } else {
                    // add
                    return visit(ctx.e(0)) + visit(ctx.e(1));
                }
            }
            return visitChildren(ctx);
        }

        public Integer visitTerminal(TerminalNode node) {
            if (node.getSymbol().getType() == ExprParser.INT) {
                return Integer.parseInt(node.getText());
            }
            return 0;
        }
    }

    public static void main(String[] args) throws IOException {
        String inputFile = null;
        if (args.length>0) {
            inputFile = args[0];
        }
        InputStream is = System.in;
        if (inputFile != null) {
            is = new FileInputStream(inputFile);
        }
        CharStream input = CharStreams.fromStream(is);
        ExprLexer lexer = new ExprLexer(input);
        CommonTokenStream tokenStream = new CommonTokenStream(lexer);
        ExprParser parser = new ExprParser(tokenStream);
        parser.setBuildParseTree(true);
        ParseTree tree = parser.s();
        // show tree in text form
        System.out.println(tree.toStringTree(parser));
        EvalVisitor evalVisitor = new EvalVisitor();
        int result = evalVisitor.visit(tree);
        System.out.println("visitor result = " + result);
    }

}
